#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;
//使用线程实现从a到b的累加
class Request
{
public:
    int _start;
    int _end;
    string _threadname;

    Request(int start, int end, string name)
    :_start(start)
    ,_end(end)
    ,_threadname(name)
    {}
};

class Response
{
public:
    int _val;
    int _exitcode;

    Response(int val, int exitcode)
    :_val(val)
    ,_exitcode(exitcode)
    {}
};

void* cal(void* arg)
{
    Request* rq = (Request*)arg;
    Response* rsp = new Response(0, 0);
    for(int i = rq->_start; i <= rq->_end; i++)
    {
        usleep(100000);
        rsp->_val += i;
        cout << rq->_threadname << " pid:" << getpid() << " operate" <<": ret += " << i << endl;
    }
    //线程间共用堆，把主线程的数据释放
    delete rq;
    return rsp;
}

int main()
{
    pthread_t tid;
    Request* rq = new Request(0,20,"mythread");
    //创建线程
    cout << "main thread pid:" << getpid() << " create thread" << endl;
    pthread_create(&tid, nullptr, cal, (void*)rq);
    void* ret;
    //等待线程,获取结果
    pthread_join(tid, &ret);
    Response* rsp = (Response*)ret;
    cout << rq->_threadname <<" cal ret = " << rsp->_val << " exitcode = " << rsp->_exitcode << endl; 
    delete rsp;
    return 0;
}